from django.shortcuts import render, HttpResponse, redirect
from db.models import *
import json
from utils import aliyunsms, restful
# djanog自带的加密解密模块
from django.contrib.auth.hashers import make_password, check_password
from utils.forms import RegisterForm
from django.views import View
# 导入缓存对象
from django.core.cache import cache
import redis
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url
import json, requests
from django.contrib import auth
from utils.django_redis_cc import conn
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, SignatureExpired  # 生成加密临时身份令牌的包
from django.core.mail import send_mail  # django自带发邮件的模块
from celery_tasks.tasks import send_register_active_email  # 导入异步发邮箱


def login(request):
    return render(request, 'login/login.html')


def check_phone(request):
    """
    手机效验通过发送短信
    """
    phone = request.GET.get('phone')
    code = request.GET.get('code')
    print(phone, 'check_phone')
    user_info = User.objects.filter(phone=phone).values()
    user_list = []
    # print(type(user_info))
    # print(len(user_info))
    if len(user_info) == 0:
        # 发送短信
        # 2 生成6位验证码
        code = aliyunsms.get_code(6, False)
        # 3 缓存到Redis
        cache.set(phone, code, 60)  # 60s有效期
        # 4 发短信
        result = aliyunsms.send_sms(phone, code)
        print('取值:', cache.get(phone))

        return HttpResponse(json.dumps({'message': 'OK'}))
    else:

        return HttpResponse(json.dumps({'message': '手机号已被注册'}))


# 短信验证码校验
def sms_check(request):
    # /duanxin/sms_check/?phone=xxx&code=xxx
    # 1. 电话和手动输入的验证码
    phone = request.GET.get('phone')
    # 2. 获取redis中保存的code
    # print('缓存中是否包含:', cache. has_key(phone))
    print('取值:', cache.get(phone))
    cache_code = cache.get(phone)
    # 把数据库获取的验证码传到前台;去前台进行判断
    return HttpResponse(json.dumps({'message': cache_code}))


# 判断注册是否成功
def register(request):
    phone = request.GET.get('phone')
    pwd = request.GET.get('pwd')
    email = request.GET.get('email')
    # print(email, '邮箱...........')
    cache_code = cache.get(phone)
    if cache_code:
        user = User.objects.create_user(phone=phone, password=pwd, username=phone)
        user.status = Status.objects.get(id=2)
        user.save()
        UserInfo.objects.create(user_id=user.id,
                                head_photo='http://pic32.nipic.com/20130813/3347542_160503703000_2.jpg',
                                vip_id=1, sex_id=3)
        # 对用户名进行加密处理
        serializer = Serializer(settings.SECRET_KEY, 3600)
        # print(serializer, 'bbbbbbbbbbbbb')
        info = {'confirm': user.id}
        # print(info, '55555555555')
        token = serializer.dumps(info).decode('utf-8')
        # print(token, '*********')
        # 发送邮件注意改成自己的邮箱;不然或报错
        send_register_active_email.delay([email], user.username, token)
        return HttpResponse(json.dumps({'result': 'OK'}))
    else:
        return HttpResponse(json.dumps({'result': 'NO'}))


def login_check_phone(request):
    """
    登录检查手机号
    """
    phone = request.GET.get('phone')
    pwd = request.GET.get('pwd')
    # print(phone, 'check_phone')
    # print(pwd)

    user_info = User.objects.filter(phone=phone).values()
    user_list = []
    if len(user_info) == 0:
        return HttpResponse(json.dumps({'result': user_list}))

    for x in user_info:
        b = {'phone': x['phone']}
        user_list.append(b)
    return HttpResponse(json.dumps({'result': user_list}))


# 登录检测密码
def login_check_pwd(request):
    phone = request.GET.get('phone')
    pwd = request.GET.get('pwd')

    # print(phone, 'check_phone')
    # print(pwd)
    user_info = User.objects.filter(phone=phone).values()
    user = User.objects.filter(phone=phone)[0]
    # print(user_info[0]['password'])
    if len(user_info) == 0:
        return HttpResponse(json.dumps({'result': 'False'}))

    user_pwd = check_password(pwd, user_info[0]['password'])
    # print(user_pwd)

    if user_info[0]['status_id'] == 1:
        if user_pwd == True:
            request.session['phone'] = phone
            auth.login(request, user)
            return HttpResponse(json.dumps({'result': 'OK'}))
        elif user_pwd == False:
            return HttpResponse(json.dumps({'result': '密码错误'}))

    else:
        return HttpResponse(json.dumps({'result': '请去邮箱激活账号'}))


# 激活账户:
def login_activate(request, token):
    serializer = Serializer(settings.SECRET_KEY, 3600)
    try:
        # 获取要激活用户的ID
        info = serializer.loads(token)
        user_id = info['confirm']
        user = User.objects.get(id=user_id)
        user.status_id = 1
        user.save()
        # 跳转到登录页面
        return redirect('login:login')
    except SignatureExpired:
        return render(request, 'goods/error404.html')


# 登录主页
def login_index(request):
    if request.method == 'POST':
        return render(request, 'goods/index.html')
    else:
        return render(request, 'login/login.html')
